let websock = null

export function initWebSocket(token) { // 初始化weosocket
  // ws地址
  const wsuri = process.env.VUE_APP_WEBSOCKET_BASE_API

  console.log(wsuri)

  websock = new WebSocket('ws://127.0.0.1:8081/UserWebSocket/' + token)

  websock.onmessage = function(e) {
    websocketonmessage(e)
  }
  websock.onclose = function(e) {
    websocketclose(e)
  }
  websock.onopen = function(e) {
    websocketOpen(e)
  }

  // 连接发生错误的回调方法
  websock.onerror = function() {
    console.log('WebSocket连接发生错误')
  }
}

// 实际调用的方法
export function sendSock(agentData) {
  if (websock.readyState === websock.OPEN) {
    // 若是ws开启状态
    websocketsend(agentData)
  } else if (websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态，则等待1s后重新调用
    setTimeout(function() {
      sendSock(agentData)
    }, 1000)
  } else {
    // 若未开启 ，则等待1s后重新调用
    setTimeout(function() {
      sendSock(agentData)
    }, 1000)
  }
}

// 数据接收
function websocketonmessage(e) {
  console.log(e.data)
}

// 数据发送
function websocketsend(agentData) {
  websock.send(JSON.stringify(agentData))
}

// 关闭
function websocketclose(e) {
  console.log('connection closed (' + e.code + ')')
}

function websocketOpen(e) {
  console.log('连接成功')
}

